<?php
namespace app\admin\model;

/**
 * 管理员模型
 */
class Manager extends Base
{
    protected $insert = ['reg_time', 'reg_ip'];

    protected function setRegTimeAttr()
    {
        return request()->time();
    }

    protected function setRegIpAttr()
    {
        return request()->ip(1);
    }

    public function login($username, $password, $code)
    {
        if(empty($this->get(['username' => $username])))
        {
            $this->error = "数据错误！";
            return false;
        }
        $info = $this->get(['username' => $username])->toArray();
        
        if (empty($info) || $info['status'] != 1) {
            $this->error = '用户不存在或者被禁用!';
            return false;
        }
        if ($info['password'] !== think_ucenter_md5($password, MANAGER_AUTH_KEY)) {

            $this->error = "密码错误！";

            return false;
        }

        if (!captcha_check($code)) {

            $this->error = "验证码错误！";

            return false;
        };

        $this->_afterlogin($info);
        return $info;
    }

    /**
     * 保存登录状态
     * @param type $info
     */
    private function _afterlogin($info)
    {
        $data = [
            'id'              => $info['id'],
            'last_login_time' => request()->time(),
            'last_login_ip'   => request()->ip(1),
            'login'           => ['exp', '`login`+1'],
        ];
        $this->update($data);
        unset($info['password']);
        session('user_auth', $info);
        session('user_auth_sign', data_auth_sign($info));
    }

    /**
     * 更新个人信息
     */
    public function updateinfo($data)
    {
        $this->allowField(true);
        $this->isUpdate = true;
        if (isset($data['password'])) {
            $data['password'] = think_ucenter_md5($data['password'], MANAGER_AUTH_KEY);
        }
        return $this->save($data);
    }

    /**
     * 新增/更新 自动判断
     * @author fenghao <303529990@qq.com>
     * @param type $data
     */
    public function edit($data)
    {
        $this->allowField(true);
        if (isset($data[$this->getPk()])) {
            $this->isUpdate = true;
        }
        if (isset($data['password'])) {
            if (empty($data['password'])) {
                unset($data['password']);
            } else {
                $data['password'] = think_ucenter_md5($data['password'], MANAGER_AUTH_KEY);
            }
        }
        return $this->save($data);
    }

}
